/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.AreaDAO;
import com.cashmate.hibernate.dao.DccrDAO;
import com.cashmate.hibernate.dao.PastDueListingDAO;
import com.cashmate.hibernate.pojo.Areas;
import com.cashmate.hibernate.pojo.Dccr;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Pastduelisting;
import com.cashmate.hibernate.pojo.Performance;
import com.cashmate.hibernate.pojo.Summary;
import com.cashmate.utilities.IncentiveObject;
import com.opensymphony.xwork2.ActionSupport;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author dean
 */
public class ChooseIncentive extends ActionSupport {

    private static final Logger logger = Logger.getLogger(ChooseIncentive.class);
    private static final Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
//    private static final Branches b = (Branches) ServletActionContext.getRequest().getSession().getAttribute("branch");
    private static final DccrDAO dccrdao = (DccrDAO) ServletActionContext.getServletContext().getAttribute("dccrDAO");
    private static final AreaDAO areadao = (AreaDAO) ServletActionContext.getServletContext().getAttribute("areaDAO");
    private static final PastDueListingDAO pastdao = (PastDueListingDAO) ServletActionContext.getServletContext().getAttribute("pastdao");
    private String monthandbranch;
    private String branch;
    private String month;
    private String year;
    private InputStream inputStream;

    @Action(value = "/choose-incentive", results = {
        @Result(name = "success", type = "stream", params = {"inputName", "inputStream", "contentType", "text/html"})
    })
    @Override
    public String execute() throws Exception {
        try {
            if (monthandbranch != null) {
                String[] parsed = monthandbranch.split("-");
                month = parsed[0];
                year = parsed[1];
                branch = parsed[2];
                int branchid = Integer.parseInt(branch);
                DetachedCriteria criteria = DetachedCriteria.forClass(Dccr.class);
                criteria.add(Restrictions.eq("branchid", branchid));
                criteria.add(Restrictions.like("dategenerated", month + "/%/" + year));
                criteria.add(Restrictions.eq("isactive", true));

                DetachedCriteria criteria2 = DetachedCriteria.forClass(Pastduelisting.class);
                criteria2.add(Restrictions.eq("branchid", branchid));
                criteria2.add(Restrictions.eq("isactive", true));

                int count = dccrdao.countByCriteria(criteria);
                criteria.setProjection(null);
                criteria.setResultTransformer(Criteria.ROOT_ENTITY);

                int count2 = pastdao.countByCriteria(criteria);
                criteria.setProjection(null);
                criteria.setResultTransformer(Criteria.ROOT_ENTITY);

                List<IncentiveObject> incentiveList = null;
                List<Pastduelisting> pastDueList = new LinkedList<Pastduelisting>();
                if (count2 > 0) {
                    pastDueList = pastdao.findByCriteria(criteria2);
                }

                GridMonthperf gm = new GridMonthperf();
                double totalOverall = gm.computeOverAll(dccrdao.monthlyPerformanceProcedure(Integer.parseInt(month), Integer.parseInt(year), branchid, null)).getTotalperarea();
                if (count > 0) {
                    criteria.setProjection(Projections.distinct(Projections.max("dategenerated")));
                    String date = dccrdao.findSingleProjectedCriteria(criteria).toString();
                    System.out.println(date);
                    criteria.setProjection(null);
                    criteria.setResultTransformer(Criteria.ROOT_ENTITY);

                    incentiveList = new LinkedList<IncentiveObject>();
                    List<Areas> areaList = areadao.getAreasPerBranch(branchid);
                    for (Areas a : areaList) {
                        List<Summary> summaryList = dccrdao.weekPerformanceProcedure(date, branchid, a.getAreacode());
                        List<Performance> performanceList = dccrdao.monthlyPerformanceProcedure(Integer.parseInt(month), Integer.parseInt(year), branchid, a.getAreacode());
                        IncentiveObject io = new IncentiveObject();
                        io.setAreacode(a.getAreacode());
                        io.setCc(a.getEmployees().getName());
                        double totalRate = 0.0;
                        double totalSales = 0.0;
                        double totalPn = 0.0;

                        for (Performance p : performanceList) {
                            io.setTotalcashollection(io.getTotalcashollection() + p.getTotalcutoffcollection());
                            totalRate += p.getRating();
                        }
                        totalRate = totalRate / performanceList.size();
                        //System.out.println("asdasdasdasdasdasdas: "+totalRate);
                        if (totalRate < 85.0) {
                            io.setRate(0);
                        } else if (totalRate <= 90.99) {
                            io.setRate(0.01);
                        } else if (totalRate <= 95.99) {
                            io.setRate(0.0125);
                        } else {
                            io.setRate(0.015);
                        }

                        for (Summary s : summaryList) {
                            totalSales += s.getPngenerated();
                            totalPn += s.getCurrentpn();
                        }
                        io.setSales(totalSales);

                        io.setGross(io.getTotalcashollection() * io.getRate());
                        io.setTotalPn(totalPn);
                        if (io.getSales() >= 500000) {
                            if (totalPn >= 1500000) {
                                io.setOfficeShare(io.getGross() * 0.2);
                            } else {
                                io.setOfficeShare(0);
                            }
                        } else {
                            io.setOfficeShare(0);
                        }

                        io.setProjIncentive(io.getGross() * 0.8);

                        if (io.getSales() >= 500000) {
                            if (totalPn >= 1500000) {
                                io.setActIncentive(io.getProjIncentive());
                            } else {
                                io.setActIncentive(0);
                            }
                        } else {
                            io.setActIncentive(0);
                        }

                        if (pastDueList.size() > 0) {
                            for (Pastduelisting pdl : pastDueList) {
                                if (pdl.getPenaltyfor() != null) {
                                    if (pdl.getPenaltyfor().equals(a.getAreacode())) {
                                        io.setNm(io.getNm() + pdl.getBalance());
                                    }
                                }
                            }
                        }

                        if (io.getActIncentive() == 0) {
                            io.setPenalty(0);
                        } else {
                            io.setPenalty(io.getNm() * io.getRate());
                        }

                        io.setPayableIncentive(io.getActIncentive() - io.getPenalty());

                        incentiveList.add(io);
                    }

                    List<IncentiveObject> hiddenRows = new LinkedList<IncentiveObject>();
                    IncentiveObject subTotal = new IncentiveObject();
                    IncentiveObject cc = new IncentiveObject();
                    IncentiveObject sec = new IncentiveObject();
                    IncentiveObject bm = new IncentiveObject();
                    IncentiveObject om = new IncentiveObject();
                    IncentiveObject ho = new IncentiveObject();
                    IncentiveObject grandTotal = new IncentiveObject();
                    IncentiveObject spares = new IncentiveObject();

                    subTotal.setAreacode("Sub-Total");
                    cc.setAreacode("CC");
                    cc.setCc("Cash Custodian");
                    sec.setAreacode("Sec");
                    sec.setCc("Secretary");
                    ho.setAreacode("HO");
                    bm.setAreacode("Branch Manager");
                    om.setAreacode("Operation Manager");
                    grandTotal.setAreacode("Grand Total");
                    spares.setAreacode("Spares");

                    double gTotalPn = 0.0;

                    for (IncentiveObject io : incentiveList) {
                        //Subtotal 1
                        subTotal.setGross(subTotal.getGross() + io.getGross());
                        subTotal.setOfficeShare(subTotal.getOfficeShare() + io.getOfficeShare());
                        subTotal.setProjIncentive(subTotal.getProjIncentive() + io.getProjIncentive());
                        subTotal.setSales(subTotal.getSales() + io.getSales());
                        subTotal.setActIncentive(subTotal.getActIncentive() + io.getActIncentive()); //To be added
                        subTotal.setPayableIncentive(subTotal.getPayableIncentive() + io.getPayableIncentive());//To be added
                        subTotal.setPenalty(subTotal.getPenalty() + io.getPenalty()); //Add *0.2 outside loop.

                        //BM
                        bm.setRate(bm.getRate() + io.getRate());
                        gTotalPn += io.getTotalPn();

                        //HIDDEN RATE AND GROSS
                        IncentiveObject io2 = new IncentiveObject();
                        io2.setSecond(true);
                        io2.setAreacode(io.getAreacode());
                        //adds.add(io2.getAreacode());
                        if (io.getRate() == 0.01) {
                            io2.setRate(0.0015);
                        } else if (io.getRate() == 0.0125) {
                            io2.setRate(0.002);
                        } else if (io.getRate() == 0.015) {
                            io2.setRate(0.0025);
                        } else {
                            io2.setRate(0.0);
                        }

                        if (totalOverall >= 80) {
                            if (io.getSales() >= 500000) {
                                io2.setGross(0.0);
                            } else {
                                if (io.getTotalPn() >= 1500000) {
                                    io2.setGross(0.0);
                                } else {
                                    io2.setGross(io.getTotalcashollection() * io2.getRate());
                                }
                            }
                        } else {
                            io2.setGross(0.0);
                        }
                        hiddenRows.add(io2);
                    }
                    //Subtotal 2
                    subTotal.setPenalty(subTotal.getPenalty() * 0.2);

                    //HO
                    ho.setGross(subTotal.getOfficeShare() * 0.45);
                    ho.setProjIncentive(subTotal.getOfficeShare() * 0.45);
                    ho.setActIncentive(subTotal.getOfficeShare() * 0.45);
                    ho.setPenalty(subTotal.getPenalty() * 0.5);
                    ho.setPayableIncentive(ho.getActIncentive() - ho.getPenalty());

                    //CC
                    cc.setGross(subTotal.getOfficeShare() * 0.27);
                    cc.setProjIncentive(subTotal.getOfficeShare() * 0.27);
                    cc.setActIncentive(subTotal.getOfficeShare() * 0.27);
                    cc.setPenalty(subTotal.getPenalty() * 0.3);
                    cc.setPayableIncentive(cc.getActIncentive() - cc.getPenalty());

                    //SEC
                    sec.setGross(subTotal.getOfficeShare() * 0.18);
                    sec.setProjIncentive(subTotal.getOfficeShare() * 0.18);
                    sec.setActIncentive(subTotal.getOfficeShare() * 0.18);
                    sec.setPenalty(subTotal.getPenalty() * 0.2);
                    sec.setPayableIncentive(sec.getActIncentive() - sec.getPenalty());

                    //BM
                    bm.setRate(bm.getRate() / incentiveList.size());
                    for (IncentiveObject io2 : hiddenRows) {
                        bm.setGross(bm.getGross() + io2.getGross());
                    }
                    if (totalOverall >= 80) {
                        if (subTotal.getSales() >= 5000000) {
                            if (gTotalPn >= 15000000) {
                                bm.setOfficeShare(bm.getGross() * 0.2);
                                bm.setProjIncentive(bm.getGross() * 0.8);
                            } else {
                                bm.setOfficeShare(0.0);
                                bm.setProjIncentive(0.0);
                            }
                            bm.setActIncentive(bm.getGross() * 0.8);
                        } else {
                            bm.setActIncentive(0.0);
                            bm.setOfficeShare(0.0);
                            bm.setProjIncentive(0.0);
                        }
                    } else {
                        bm.setOfficeShare(0.0);
                        bm.setProjIncentive(0.0);
                    }

                    if (pastDueList.size() > 0) {
                        for (Pastduelisting pdl : pastDueList) {
                            if (pdl.getPenaltyfor().equalsIgnoreCase("BM")) {
                                bm.setNm(bm.getNm() + pdl.getCurrentpn());
                            }
                        }
                    }

                    if (bm.getActIncentive() == 0) {
                        bm.setPenalty(0.0);
                    } else {
                        bm.setPenalty(bm.getNm() * bm.getRate());
                    }
                    bm.setPayableIncentive(bm.getActIncentive() - bm.getPenalty());

                    //OM
                    om.setOfficeShare(bm.getOfficeShare());
                    om.setProjIncentive(om.getOfficeShare());
                    om.setActIncentive(om.getOfficeShare());

                    if (pastDueList.size() > 0) {
                        for (Pastduelisting pdl : pastDueList) {
                            if (pdl.getPenaltyfor().equalsIgnoreCase("OM")) {
                                om.setNm(om.getNm() + pdl.getCurrentpn());
                            }
                        }
                    }

                    if (om.getActIncentive() == 0) {
                        om.setPenalty(0.0);
                    } else {
                        om.setPenalty(om.getNm() * bm.getRate());
                    }
                    om.setPayableIncentive(om.getActIncentive() - om.getPenalty());

                    //Subtotal 3
                    subTotal.setActIncentive(subTotal.getActIncentive() + ho.getActIncentive());
                    subTotal.setActIncentive(subTotal.getActIncentive() + cc.getActIncentive());
                    subTotal.setActIncentive(subTotal.getActIncentive() + sec.getActIncentive());
                    subTotal.setActIncentive(subTotal.getActIncentive() + bm.getActIncentive() + om.getActIncentive());
                    subTotal.setPayableIncentive(subTotal.getPayableIncentive() + ho.getPayableIncentive());
                    subTotal.setPayableIncentive(subTotal.getPayableIncentive() + cc.getPayableIncentive());
                    subTotal.setPayableIncentive(subTotal.getPayableIncentive() + sec.getPayableIncentive());
                    subTotal.setPayableIncentive(subTotal.getPayableIncentive() + bm.getPayableIncentive() + om.getPayableIncentive());

                    //Grand Total1
                    grandTotal.setGross(subTotal.getGross() + bm.getGross());
                    grandTotal.setOfficeShare(cc.getProjIncentive() + ho.getProjIncentive() + sec.getProjIncentive());
                    grandTotal.setProjIncentive(subTotal.getProjIncentive());

                    //Spares
                    spares.setGross(grandTotal.getOfficeShare() * 0.1);
                    spares.setProjIncentive(grandTotal.getOfficeShare() * 0.1);
                    spares.setActIncentive(grandTotal.getOfficeShare() * 0.1);
                    spares.setPayableIncentive(spares.getActIncentive() - spares.getPenalty());
                    
                    //Subtotal 4
                    subTotal.setActIncentive(subTotal.getActIncentive() + spares.getActIncentive());
                    subTotal.setPayableIncentive(subTotal.getPayableIncentive() + spares.getPayableIncentive());
                    
                    //Grand Total2
                    grandTotal.setActIncentive(subTotal.getActIncentive());
                    grandTotal.setPayableIncentive(subTotal.getPayableIncentive());
                    
                    //ADD ALL HERE
                    incentiveList.add(ho);
                    incentiveList.add(cc);
                    incentiveList.add(sec);
                    incentiveList.add(spares);
                    for (IncentiveObject io2 : hiddenRows) {
                        incentiveList.add(io2);
                    }
                    incentiveList.add(bm);
                    incentiveList.add(om);
                    incentiveList.add(subTotal);
                    incentiveList.add(grandTotal);


                    ServletActionContext.getRequest().getSession().setAttribute("incentiveList", incentiveList);

                    inputStream = new StringBufferInputStream("<script type=\"text/javascript\">"
                            + "window.location=\"incentive.jsp?branch=" + branch + "&month=" + month + "&year=" + year + "\";"
                            + "</script>");
                }
            }
        } catch (Exception e) {
            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + e.getLocalizedMessage(), e);
            } else {
                logger.fatal(e.getLocalizedMessage(), e);
            }
            e.printStackTrace();
            addActionError(e.getLocalizedMessage());
        } finally {
            DccrDAO.close();
            AreaDAO.close();
            PastDueListingDAO.close();
        }
        return SUCCESS;
    }

    public void setMonthandbranch(String monthandbranch) {
        this.monthandbranch = monthandbranch;
    }

    public InputStream getInputStream() {
        return inputStream;
    }
}
